﻿package com.jianghu.dto;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;

public class BaseDto {
	
	/**
	 * 把一个Object中所有的field, 包括公共、保护、默认（包）访问和私有字段，但不包括继承的字段, 
	 * 映射成一个HashMap<String, Object>(key is fieldName, value is field value).<br>
	 * 如果此field 为非public修饰且有对应的getter方法, 则调用. 如果没有对应的getter 方法则取原值<br>
	 * Example: BaseDto.getFieldMap(new Foo(), Foo.class())
	 * @param obj
	 * @param clazz
	 * @return
	 */
	public static HashMap<String, Object> getFieldMap(Object obj, Class clazz){
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field f = fields[i];
				f.setAccessible(true);
				String fieldName = f.getName();
				Object value = f.get(obj);
				
				if(f.getModifiers() != Modifier.PUBLIC){
					try {
						Method getterMethod = clazz.getMethod(getGetterMethodName(fieldName));
						//the getter method
						value = getterMethod.invoke(obj);
					} catch (Exception e) {
						//e.printStackTrace();
					}
				}
				map.put(fieldName, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	public static String getGetterMethodName(String fieldName){
		char firstChar = fieldName.charAt(0);
		if(firstChar > 'a' && firstChar < 'z'){
			String s = firstChar+"";
			fieldName = fieldName.replaceFirst(s, s.toUpperCase());
		}
		return "get"+fieldName;
	}
	
}
